<template>
  <a-modal :open="open" width="1400px" centered destroy-on-close :ok-text="addOrUpdate ? (isArmy ? '登记' : '登记收费') : '确定'" @ok="onOk" @cancel="onCancel">
    <template #title>
      <div class="flex items-start pr-20">
        <span class="w-24">{{ addOrUpdate ? '入院登记' : '修改入院登记' }}</span>
        <a-radio-group
          v-if="isMedicalInsurance"
          v-model:value="tabActiveKey"
          :disabled="!addOrUpdate"
          button-style="solid"
          size="large"
          class="flex-1 -mt-2 flex justify-center"
          @change="onTabChange"
        >
          <a-radio-button v-for="item in filterType()" :key="item.name" :value="item.name">{{ item.name }}</a-radio-button>
        </a-radio-group>
      </div>
    </template>
    <div class="flex justify-between w-full">
      <div class="pr-2 mr-2 overflow-y-auto max-h-[850px] w-1/2">
        <template v-if="tabActiveKey !== '自费'">
          <BaseTitle title="医保信息">
            <div class="flex-1 flex justify-between">
              <div>
                <a-input v-if="tabActiveKey === '电子凭证'" v-model:value="kh" placeholder="请扫描电子凭证" class="w-[360px] ml-2" />
              </div>
              <a-button type="primary" @click="onReadSocialCard(false)">读卡</a-button>
            </div>
          </BaseTitle>
          <div v-if="tabActiveKey == '身份证' && inAreaCode === '02'" class="flex justify-end">
            <a-input v-model:value="idNumber" class="w-[200px] ml-2" placeholder="请输入身份证号" />
            <a-button type="primary" class="ml-2" @click="onReadSocialCard(true)">无卡识别</a-button>
          </div>
          <div class="mt-2 mb-5 flex items-center pl-10">
            <div class="w-1/2">
              <LabelValue label-class="w-[70px] font-bold" label="社保卡号" class="mb-2 font-bold" :width="240" :value="medFormState?.insureNo" />
              <LabelValue label-class="w-[70px]" label="身份证号" class="mb-2" :width="240" :value="medFormState?.brSfz" />
              <LabelValue label-class="w-[70px]" label="凭证编号" class="mb-2" :width="240" :value="medFormState?.mdtrtCertNo" tooltip />
            </div>
            <div class="w-1/2">
              <LabelValue label-class="w-[70px]" label="卡识别码" class="mb-2" :width="260" :value="medFormState?.ksbm_new" tooltip />
              <div class="flex items-center mb-2">
                <div class="w-[80px]">险种类别：</div>
                <a-input
                  v-model:value="CHSInfo.insutypeName"
                  class="w-[230px]"
                  placeholder="险种类别"
                  :disabled="!!accountQueryData"
                  allow-clear
                  @click="onClickInsureTypeName(true)"
                />
              </div>
              <LabelValue label-class="w-[90px]" label="所属统筹区" class="mb-2" :width="200" :value="CHSInfo?.insuplc_admdvs" />
            </div>
          </div>
        </template>
        <BaseTitle title="基础信息" />
        <div>
          <PatientInfoIn
            v-model:value="patientState"
            :row-data="rowData"
            :patient-type="'入院登记'"
            :show-divider-bot-info="false"
            :table-width="700"
            item-class="w-1/2"
            :search-params="{
              pyjm: patientState.brName,
              yyzt: '0'
            }"
            @change="patientFormChange"
            @changed="getBeInHospital"
          />
        </div>
      </div>
      <div class="w-1/2">
        <a-form ref="registForm" :model="registState" :label-col="{ style: { width: '110px' } }">
          <BaseTitle title="住院信息" class="w-full mb-0">
            <a-form-item label="第" name="zycs" class="flex" :rules="[{ required: true, message: '请输入入院次数' }]">
              <a-input-number v-model:value="registState.zycs" :min="1" placeholder="请输入" class="flex-1 w-20" />
              <span class="inline-block w-12 ml-2">次入院</span>
            </a-form-item>
          </BaseTitle>
          <a-form-item
            v-if="!isArmy"
            label="医疗类别"
            class="w-1/2"
            name="inpTypeCode"
            :rules="[{ required: isArmy ? false : true, message: '请选择医疗类别' }]"
          >
            <SelectItem v-model:value="registState.inpTypeCode" type="med_type" :params="{ type: '住院' }" trigger="init" placeholder="请选择" />
          </a-form-item>
          <a-form-item
            v-if="!isArmy"
            label="付费方式"
            class="w-1/2"
            name="paymentTypeCode"
            :rules="[{ required: isArmy ? false : true, message: '请选择付费方式' }]"
          >
            <a-select v-model:value="registState.paymentTypeCode" class="w-full" placeholder="请选择">
              <a-select-option v-for="(item, index) in payType" :key="index" :value="item.dictItemCode">{{ item.dictItemName }}</a-select-option>
            </a-select>
          </a-form-item>
          <!-- v-if="tabActiveKey !== '自费'" -->
          <a-form-item v-if="tabActiveKey !== '自费'" label="医保病种" class="w-full">
            <SelectTable
              v-model:value="registState.inDiseTypeName"
              type="医保病种"
              allow-clear
              :row-disabled="(row) => row.status === 1"
              placeholder="请选择"
              @select="
                ;(registState.inDiseTypeName = $event?.diseTypeName || ''),
                  (registState.inDiseTypeCode = $event?.diseTypeCode || ''),
                  (registState.outOprIcd9Code = $event?.oprCode || ''),
                  (registState.outOprIcd9Name = $event?.oprName || '')
              "
            />
          </a-form-item>

          <a-form-item label="入院科室" class="w-1/2" name="appDeptCode" :rules="[{ required: true, message: '请选择入院科室' }]">
            <!-- <SelectSection v-model:value="registState.appDeptCode" :search-params="{ yxzt: '0' }" @change="changeKsdm" /> -->
            <!-- <SelectRegistrationDepart v-model:value="registState.appDeptCode" :search-params="{ sfylks: '0' }" @change="changeKsdm" /> -->
            <a-select
              v-model:value="registState.appDeptCode"
              placeholder="请选择"
              :options="departmentList"
              :field-names="{ label: 'ksmc', value: 'ksdm' }"
              @select="changeKsdm"
            />
          </a-form-item>
          <a-form-item label="病区名称" name="wardId" class="w-1/2" :rules="[{ required: true, message: '请选择病区' }]">
            <a-select
              v-model:value="registState.wardId"
              :options="wardList"
              :field-names="{ label: 'wardName', value: 'id' }"
              placeholder="请选择"
              @change="changeArea"
            />
          </a-form-item>
          <a-form-item label="目标床位" name="bedCode" class="w-1/2" :rules="[{ required: true, message: '请选择目标床位' }]">
            <SelectTable
              v-model:value="registState.bedCode"
              :table-width="300"
              type="床位"
              placeholder="请输入"
              :search-params="{ bqid: registState.wardId }"
              :row-disabled="(row) => row.status === 2 || row.status === 1"
              @select="onSelectWard"
            />
            <!-- :search-params="{ bqid: registState.bqbh }" -->
          </a-form-item>
          <a-form-item label="入院时间" class="w-1/2">
            <a-date-picker v-model:value="registState.rysj" show-time value-format="YYYY-MM-DD HH:mm:ss" />
          </a-form-item>
          <a-form-item label="入院途径" class="w-1/2">
            <SelectItem v-model:value="registState.admissionRoadCode" type="DT00013" placeholder="请选择" />
          </a-form-item>
          <a-form-item label="入院诊断" class="w-full" name="icd10CodeName" :rules="[{ required: true, message: '请选择入院诊断' }]">
            <a-input-group compact class="w-full">
              <SelectTable v-model:value="registState.icd10CodeName" type="诊断" class="!w-2/3" @select="onSelectDiagnosis" />
              <a-form-item-rest>
                <a-input v-model:value="registState.icd10Code" class="!w-1/3" :disabled="true" placeholder="请选择" />
              </a-form-item-rest>
            </a-input-group>
          </a-form-item>
          <a-form-item label="诊断描述" name="diagnosisDesc" class="w-full" :rules="[{ required: true, message: '请输入诊断描述' }]">
            <a-input v-model:value="registState.diagnosisDesc" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="行何手术" class="w-full">
            <a-input v-model:value="registState.readyOperation" placeholder="行何手术" />
          </a-form-item>
          <a-form-item label="部位" :rules="[{ required: bwMust ? true : false, message: '请选择部位' }]" class="w-1/2">
            <!-- <a-select v-model:value="registState.bw" placeholder="请选择" mode="multiple" :max-tag-count="3" :options="positionList" allow-clear /> -->
            <SelectPartTags
              :value="{ partCode: registState.bw, partName: registState.bws }"
              multiple
              allow-clear
              show-new
              :input-or-textarea="true"
              type="部位"
              @select="onSelectParts"
            />
          </a-form-item>
          <a-form-item label="预计住院天数" class="w-1/2">
            <a-input v-model:value="registState.expectDays" placeholder="预计住院天数" />
          </a-form-item>

          <a-form-item label="责任医生" class="w-1/2">
            <SelectTable v-model:value="registState.dutyDoctorName" type="医生" placeholder="请选择" @select="onSelectYs($event, 'dutyDoctor')" />
          </a-form-item>
          <a-form-item label="住院医生" class="w-1/2">
            <SelectTable v-model:value="registState.inpDoctorName" type="医生" placeholder="请选择" @select="onSelectYs($event, 'inpDoctor')" />
          </a-form-item>
          <a-form-item label="主治医生" class="w-1/2" name="attendingDoctorName" :rules="[{ required: true, message: '请选择主治医生' }]">
            <SelectTable v-model:value="registState.attendingDoctorName" type="医生" placeholder="请选择" @select="onSelectYs($event, 'attendingDoctor')" />
          </a-form-item>
          <a-form-item label="主任(副)医生" class="w-1/2">
            <SelectTable v-model:value="registState.directorDoctorName" type="医生" placeholder="请选择" @select="onSelectYs($event, 'directorDoctor')" />
          </a-form-item>
          <a-form-item label="新生儿出生体重" class="w-1/2">
            <a-input v-model:value="registState.birthWeight" placeholder="请输入" suffix="克" />
          </a-form-item>
          <a-form-item label="新生儿入院体重" class="w-1/2">
            <a-input v-model:value="registState.inpWeight" placeholder="请输入" suffix="克" />
          </a-form-item>
          <a-form-item label="说明" class="w-full">
            <a-textarea v-model:value="registState.memo" placeholder="说明" allow-clear :rows="2" :show-count="false" />
          </a-form-item>
        </a-form>
        <div>
          <BaseTitle title="异地就医" />
          <a-form :model="registState" :label-col="{ style: { width: '130px' } }">
            <a-form-item label="就诊人群类型" class="w-full">
              <a-radio-group v-model:value="registState.patientGroupCode">
                <a-radio class="mb-2 mt-1" value="">正常</a-radio>
                <a-radio class="mb-2 mt-1" value="1">新冠肺炎确诊患者</a-radio>
                <a-radio class="mb-2 mt-1" value="2">其他国家突发公共事件</a-radio>
                <a-radio class="mb-2 mt-1" value="3">新冠肺炎疑似患者</a-radio>
                <a-radio class="mb-2 mt-1" value="4">无症状感染者</a-radio>
              </a-radio-group>
              <a-divider class="mt-1 mb-3" />
              <a-checkbox v-model:checked="registState.isThird">设计第三方标志</a-checkbox>
              <a-checkbox v-model:checked="registState.isTrauma">外伤标志</a-checkbox>
              <a-checkbox v-model:checked="registState.isReferral">门诊急诊转诊标志</a-checkbox>
            </a-form-item>
          </a-form>
        </div>
        <BaseTitle v-if="addOrUpdate && !isArmy" title="费用信息" />
        <a-form v-if="addOrUpdate && !isArmy" :model="moneyFrom" :label-col="{ style: { width: '100px' } }">
          <a-form-item label="预收款" class="w-full" :rules="[{ required: true, message: '请输入预收款' }]">
            <div class="flex items-center">
              <a-input-number v-model:value="moneyFrom.ssje" prefix="￥" :min="0" class="w-1/2 mr-2" placeholder="预收款金额" />
              <p v-if="ksInfo.depositLimit" class="text-zinc-600 w-1/2 my-0">{{ ksInfo.ksmc }}最少缴纳{{ ksInfo.depositLimit }}元</p>
              <p v-else class="text-zinc-600 w-1/2 my-0">未设置最少缴纳金额</p>
            </div>
          </a-form-item>
          <a-form-item label="备注" class="w-full">
            <a-input v-model:value="moneyFrom.memo" placeholder="备注" allow-clear />
          </a-form-item>
        </a-form>
      </div>
    </div>
  </a-modal>
  <ChargeModal
    v-model:open="chargeOpen"
    :business-data="{ ysje: moneyFrom.ssje }"
    :is-show-in-title="false"
    :is-show-amount="false"
    @success="onChargeSuccess"
  />
  <!-- 账户查询五期 -->
  <AccountQueryFive v-model:open="accountQueryFiveOpen" :resource-data="accountQueryData" />
  <!-- 账户查询六期 -->
  <AccountQuerySix v-model:open="accountQuerySixOpen" :resource-data="accountQueryData" :select="CHSInfo" @ok="onSelectCHS" />
</template>
<script setup>
import { ref, watch, onMounted, createVNode, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import { getAgeUnit } from '@/utils/format'
import { getSystemConfig } from '@/utils/systemConfig'
import PatientInfoIn from '@/components/business/PatientInfoIn'
import ChargeModal from '@/components/ChargeModal'
import useUserStore from '@/store/user'
import AccountQueryFive from '../components/AccountQueryFive.vue'
import AccountQuerySix from '../components/AccountQuerySix.vue'

const { empId } = useUserStore()

const emit = defineEmits(['update:open', 'success'])
const isMedicalInsurance = ref(false) //是否启用医保
const patientState = ref({
  brName: ''
})
const chargeOpen = ref(false)
const registerPrice = ref(0)
const ksInfo = ref({})
const moneyFrom = ref({})
// const statusZyh = ref(false)
const wardList = ref([])
const registState = ref({})
// const patientZyhStatus = ref(false)
const isArmy = ref(false) //是否jun用
const bwMust = getSystemConfig('INP_ADMISSION_REGISTRATION_MUST_CHOOSE_PART') === '1' //入院申请及登记时部位必选
const props = defineProps({
  open: Boolean,
  title: {
    type: String,
    default: '入院登记'
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  addOrUpdate: {
    desc: '入院登记或修改入院登记', //true add  false update
    type: Boolean,
    default: true
  }
})
watch(
  () => props.open,
  (val) => {
    if (val) {
      getWardData()
      initPatientInfo(props.rowData)
    } else {
      patientState.value = {}
      registState.value = {}
      CHSInfo.value = {}
    }
  }
)
const initPatientInfo = (val) => {
  if (val) {
    const rowData = JSON.parse(JSON.stringify(val))
    patientState.value = rowData
    registState.value = {
      ...rowData,
      icd10Code: rowData.outpIco10code,
      icd10CodeName: rowData.outpIco10codeName,
      diagnosisDesc: rowData.outpIco10codeName,
      isThird: rowData.isThird === '1' ? true : false,
      isTrauma: rowData.isTrauma === '1' ? true : false,
      isReferral: rowData.isReferral === '1' ? true : false
    }
    moneyFrom.value.ssje = rowData.depositAmount
    registState.value.bw = rowData.bw ? rowData.bw : undefined
    // if (rowData.admissionCode) {
    //   statusZyh.value = true
    // } else {
    //   statusZyh.value = false
    // }
    if (patientState.value.brName && !patientState.value.pyjm) {
      nextTick(() => {
        getZjm(patientState.value.brName)
      })
    }
    if (registState.value.appDeptCode) changeKsdm()
  } else {
    // statusZyh.value = true
    patientState.value = {}
    registState.value = {}
    moneyFrom.value.ssje = ''
  }
  if (props.addOrUpdate) {
    registState.value.rysj = dayjs().format('YYYY-MM-DD HH:mm:ss')
    if (!registState.value.inpTypeCode) registState.value.inpTypeCode = getSystemConfig('INP_DEFAULT_MEDICAL_TYPE_CODE')
  } else {
    registState.value.rysj = val?.admissionTime
  }
  getPayTypeData()
}

// 获取预约病区
const getWardData = async () => {
  const { code, data } = await post('/operation/opex/getWardInfoList', { wardTypeCodes: ['QYLB001'] })
  if (code !== 0) return message.error(code)
  wardList.value = data
}
// const patientSelect = (e) => {
//   patientZyhStatus.value = e
// }
const patientFormChange = (val) => {
  registState.value = {
    ...val,
    icd10Code: val.outpIco10code,
    icd10CodeName: val.outpIco10codeName,
    isThird: val.isThird === '1' ? true : false,
    isTrauma: val.isTrauma === '1' ? true : false,
    isReferral: val.isReferral === '1' ? true : false
  }
  patientState.value = val
  // if (val.admissionCode && patientZyhStatus.value) {
  //   statusZyh.value = true
  // } else {
  //   statusZyh.value = false
  // }
  registState.value.bw = val.bw ? val.bw : undefined
  registState.value.rysj = dayjs().format('YYYY-MM-DD HH:mm:ss')
  registState.value.diagnosisDesc = registState.value.icd10CodeName
}
const registForm = ref(null)
const onOk = async () => {
  await registForm.value.validateFields()
  if (!getCheck()) return
  if (!props.addOrUpdate || isArmy.value) {
    onChargeSuccess({})
    return
  }
  const params = {
    change: 0,
    cxkzf: 0,
    fbyh: 0,
    ssje: '0.00',
    wxzf: '0.00',
    wyzf: 0,
    xjzf: 0,
    xykzf: 0,
    yhje: '0.00',
    ysje: '0.00',
    zfbzf: 0
  }
  if (moneyFrom.value.ssje < ksInfo.value.depositLimit) {
    const msg = '预收款金额不足，' + ksInfo.value.ksmc + '最少缴纳' + ksInfo.value.depositLimit + '元'
    Modal.confirm({
      title: '提示',
      okText: '继续',
      centered: true,
      maskClosable: true,
      width: 560,
      cancelText: '取消',
      icon: createVNode(ExclamationCircleOutlined, { style: 'color:red' }),
      content: createVNode('div', { style: 'margin:24px 0;font-size:15px' }, msg),
      onOk() {
        if (moneyFrom.value.ssje === 0) {
          onChargeSuccess(params)
        } else {
          registerPrice.value = moneyFrom.value.ssje
          chargeOpen.value = true
        }
      }
    })
  } else {
    if (ksInfo.value.depositLimit <= 0 && moneyFrom.value.ssje === 0) {
      onChargeSuccess(params)
    } else {
      registerPrice.value = moneyFrom.value.ssje
      chargeOpen.value = true
    }
  }
}
const getCheck = () => {
  if (!patientState.value.brName) {
    message.error('请填写姓名')
    return false
  }
  if (!patientState.value.admissionCode) {
    message.error('请生成住院号')
    return false
  }
  if (!patientState.value.provincesCityDistrict) {
    message.error('请选择家庭地址')
    return false
  }
  if (!patientState.value.brJtdz) {
    message.error('请填写详细地址')
    return false
  }
  if (!patientState.value.brJg) {
    message.error('请选择籍贯')
    return false
  }
  // if (!patientState.value.brCsd) {
  //   message.error('请选择出生地')
  //   return false
  // }
  // if (patientState.value.admissionCode.length !== 10) {
  //   message.error('住院号格式错误')
  //   return false
  // }
  if (bwMust) {
    if (!registState.value.bw || registState.value.bw.length <= 0) {
      message.error('请选择部位')
      return false
    }
  }
  if (!moneyFrom.value.ssje && moneyFrom.value.ssje !== 0 && props.addOrUpdate && !isArmy.value) {
    message.error('请输入预收款金额')
    return false
  }
  return true
}
const onSelectDiagnosis = (diagnosis) => {
  registState.value.icd10CodeName = diagnosis.zdmc
  registState.value.icd10Code = diagnosis.zddm
}
const changeKsdm = async () => {
  const { data, code } = await post('/operation/opex/getInpDeptDepositSetList', {
    mcbh: '',
    ksdm: registState.value.appDeptCode
  })
  if (code !== 0) return
  if (data.length > 0) {
    ksInfo.value = data[0]
  }
}
const onChargeSuccess = async (params) => {
  delete patientState.value.brZlxm
  const { data, code, msg } = await post(
    '/inp/zydj/doSaveInpAdmission',
    {
      whetherInsured: tabActiveKey.value === '自费' ? 0 : 1, //是否医保
      medFormState: medFormState.value,
      inpRegistrationRequest: {
        paymentTypeCode: registState.value.paymentTypeCode,
        inplsh: registState.value.inplsh,
        inpTypeCode: registState.value.inpTypeCode,
        mdtrtCertType: cardTypeEnum[tabActiveKey.value]?.mdtrtCertType,
        mdtrtCertNo: medFormState.value.mdtrtCertNo,
        med_type: registState.value.inpTypeCode,
        insutype: CHSInfo.value.insutype,
        ybkh: medFormState.value.insureNo
      },
      inpRecordInfol: {
        admissionCode: patientState.value.admissionCode,
        admissionEmpId: empId,
        admissionRoadCode: registState.value.admissionRoadCode,
        admissionTime: registState.value.rysj,
        appointmentLsh: patientState.value.lsh,
        brId: patientState.value.brId,
        expectDays: registState.value.expectDays,
        icd10Code: registState.value.icd10Code,
        outpIco10code: registState.value.outpIco10code,
        lastAttendingDoctor: registState.value.attendingDoctor,
        lastBedCode: registState.value.bedCode,
        lastDirectorDoctor: registState.value.directorDoctor,
        lastDutyDoctor: registState.value.dutyDoctor,
        lastInpDoctor: registState.value.inpDoctor,
        lastDeptCode: registState.value.appDeptCode,
        lastWardId: registState.value.wardId,
        readyOperation: registState.value.readyOperation,
        cmemo: registState.value.memo,
        inpFrequency: registState.value.zycs,
        diagnosisDesc: registState.value.diagnosisDesc,
        birthWeight: registState.value.birthWeight,
        inpWeight: registState.value.inpWeight,
        patientGroupCode: registState.value.patientGroupCode,
        isThird: registState.value.isThird ? '1' : '0',
        isTrauma: registState.value.isTrauma ? '1' : '0',
        isReferral: registState.value.isReferral ? '1' : '0',
        inplsh: registState.value.inplsh,
        inpRegistrationCategory: forMatTab(tabActiveKey.value), //入院登记类别 自费：0 | 社保卡：1 | 身份证：2 | 电子凭证：3 | 刷脸授权：4 | 终端扫码：5
        lastNurseLevelId: registState.value.lastNurseLevelId,
        inDiseTypeName: registState.value.inDiseTypeName,
        inDiseTypeCode: registState.value.inDiseTypeCode,
        outOprIcd9Code: registState.value.outOprIcd9Code,
        outOprIcd9Name: registState.value.outOprIcd9Name
      },
      inpRecordPartList: registState.value.bw,
      patientInfo: {
        ...patientState.value,
        brAge: getAgeUnit(patientState.value.brAge).brAge,
        ageUnit: getAgeUnit(patientState.value.brAge).ageUnit
      },
      inplsh: registState.value.inplsh
    },
    { loading: true }
  )
  if (code !== 0) return message.error(msg || '请求失败')
  if (props.addOrUpdate) {
    if (isArmy.value) {
      message.success(msg || '登记成功')
      chargeOpen.value = false
      emit('success')
      onCancel()
    } else {
      saveDeposit(data.inplsh, params)
    }
  } else {
    message.success(msg || '修改成功')
    chargeOpen.value = false
    emit('success')
    onCancel()
  }
}

const saveDeposit = async (inplsh, params) => {
  const { code, msg, data } = await post('/inp/inpComprehensive/doDepositCharge', {
    inplsh: inplsh,
    ...params,
    memo: moneyFrom.value.memo
  })
  if (code !== 0) return message.error(msg || '请求失败')
  message.success(msg || '登记成功')
  chargeOpen.value = false
  emit('success')
  onPrint(data)
  // onPrintProve(data) // 打印住院证
  onCancel()
}
const onPrint = async (lshData) => {
  const { code, msg, data } = await post('/inp/Print/inpDepositSlipPrint', { lsh: lshData?.lsh, inplsh: lshData.inplsh, sfbd: 0 })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
// // 打印住院证
// const onPrintProve = async (params) => {
//   const { code, msg, data } = await post('/inp/Print/hospitalizationCertificatePrint', { inplsh: params.inplsh })
//   if (code !== 0) return message.error(msg)
//   window.openExe?.rpt(data) //调用winform打印
// }

const forMatTab = (val) => {
  if (val === '自费') return 0
  if (val === '社保卡') return 1
  if (val === '身份证') return 2
  if (val === '电子凭证') return 3
  if (val === '刷脸授权') return 4
  if (val === '终端扫码') return 5
}
const onCancel = () => {
  emit('update:open', false)
  tabActiveKey.value = '自费'
  kh.value = ''
  medFormState.value = {}
  CHSInfo.value = {}
  registState.value = {}
}
const onSelectParts = (val) => {
  registState.value.partCode = val?.partCode || []
  registState.value.partName = val?.partName || ''
}
const changeArea = () => {
  registState.value.bedCode = ''
}
const getZjm = async (name) => {
  const { data, code } = await post('/common/util/getPinyin', { name: name })
  if (code === 0) {
    patientState.value.pyjm = data
  }
}
const onSelectWard = (select) => {
  registState.value.bedCode = select.bedCode
}
const onSelectYs = (select, key) => {
  registState.value[key] = select.empId
  registState.value[key + 'Name'] = select.empName
}

// 获取科室
const departmentList = ref([])
const getDepartmentList = async () => {
  const { code, data } = await post('/outp/mzdj/getDeptInfoList', { sfylks: '0' })
  if (code !== 0) return
  departmentList.value = data
}

onMounted(() => {
  callWindow()
  getLoginUserDepartment()
  getDepartmentList()
  isMedicalInsurance.value = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1' //是否启用医保
  inAreaCode.value = getSystemConfig('NMI_REGION_CODE') //00:国家医保101:上海医保 默认为 00
  isArmy.value = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
})
// 医保结算修改
const tabActiveKey = ref('自费')
const isGb = ref(true) //false 五期 true 国平
const onTabChange = async () => {
  tabActiveKey.value === '自费' && (CHSInfo.value = {})
  callWindow()
}
const CHSInfo = ref({
  certno: '',
  // med_type: '21', //普通住院
  psn_cert_type: '1' //身份证
})
const cardTypeEnum = {
  自费: {
    mdtrtCertType: '0001',
    area: '*'
  },
  社保卡: {
    mdtrtCertType: '03',
    area: '*'
  },
  身份证: {
    mdtrtCertType: '02',
    area: '*'
  },
  电子凭证: {
    mdtrtCertType: '01',
    area: '*'
  },
  刷脸授权: {
    mdtrtCertType: '01',
    area: '00'
  },
  终端扫码: {
    mdtrtCertType: '01',
    area: '00'
  },
  磁卡: {
    mdtrtCertType: '00',
    area: '01'
  },
  特殊人员: {
    mdtrtCertType: '06',
    area: '01'
  }
}
// jsonStr.value =
//   '{"ybkRquese":{"cardtype":"1","carddata":""},"ybkResonse":{"xb":"女","sfzh":"310104195701174561","lxdh":"65537984","txdz":"淮海中路1799号","yzbm":"200233","klbbz":"1","kh":"D06073096","xm":"张美芳","zhbz":"2000000000000000","dnzhye":0.0,"lnzhye":0.0,"mzzfdxjzfljs":300.0,"zyzfxxzfljs":1200.0,"mzzfdde":300.0,"zyzfdde":1200.0,"tczffdxde":610000.0,"qfxsfdxxfylj":24274.97,"jlch":"100806419510","mzylbkdd":"","br_id":"D06073096","xzqh":"","ybsqjmbz":"1"}}'
const jsonStr = ref('')
const readCardResult = ref('')
const kh = ref('')
const payType = ref([])
const loginUserDepartment = ref([])
const inAreaCode = ref('00') //00:国家医保101:上海医保 默认为 00
const getLoginUserDepartment = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
  loginUserDepartment.value = res?.data || {}
}
const callWindow = async () => {
  if (tabActiveKey.value === '自费') return
  let businessType = 0
  if (tabActiveKey.value === '身份证' || tabActiveKey.value === '社保卡') {
    businessType = 1
  } else if (['电子凭证', '刷脸授权', '终端扫码'].includes(tabActiveKey.value)) {
    businessType = '01103'
  } else if (tabActiveKey.value === '磁卡') {
    businessType = '00'
  }
  const res1 = await post('/outp/mzdj/getMedicareCardSettinglnfo', {
    businessType,
    officeid: loginUserDepartment.value.ksdm
  })
  if (res1.code !== 0) return message.error(res1.msg)
  jsonStr.value = res1.data
}
//获取付费方式
const getPayTypeData = async () => {
  // DT00289
  const { code, data, msg } = await post('/operation/opex/getDictCommonItemList', {
    dictCommonCode: 'DT00289',
    status: 1
  })
  if (code !== 0) return message.error(msg || '获取付费方式失败')

  payType.value = data
  if (payType.value && payType.value.length > 0 && !isMedicalInsurance.value) {
    const payTypeBank = payType.value.filter((item) => {
      return item.dictItemName === '自费'
    })
    if (payTypeBank && payType.value.length > 0 && !registState.value.paymentTypeCode) {
      registState.value.paymentTypeCode = payTypeBank[0].dictItemCode
    }
  }
}
const accountQueryData = ref({})
const medFormState = ref({})
const isSixSelect = ref(false)
const accountQuerySixOpen = ref(false)
const accountQueryFiveOpen = ref(false)
const idNumber = ref('')
const onReadSocialCard = async (flag = false) => {
  let res = {}
  if (flag) {
    //无身份证识别
    if (!idNumber.value) return message.error('请输入身份证号')
    res = await post('/outp/mzdj/getReadPatientInfo', {
      type: 'ZYDJ',
      brName: '',
      brSfz: idNumber.value
    })
  } else {
    if (tabActiveKey.value === '社保卡') {
      readCardResult.value = window.openExe?.readYBK(jsonStr.value) //调用壳
    } else if (tabActiveKey.value === '身份证') {
      readCardResult.value = window.openExe?.readSFZ(jsonStr.value) //调用壳
    } else if (tabActiveKey.value === '电子凭证') {
      readCardResult.value = window.openExe?.readDZPZ(kh.value, jsonStr.value) //调用壳
    } else if (tabActiveKey.value === '刷脸授权' || tabActiveKey.value === '终端扫码') {
      const params = JSON.parse(jsonStr.value)
      const paramsJson = JSON.stringify({
        ...params,
        fficeid: loginUserDepartment.value.ksdm,
        officename: loginUserDepartment.value.ksmc,
        slurl: getSystemConfig('FACE_SWIPING_URL')
      })
      readCardResult.value = tabActiveKey.value === '刷脸授权' ? window.openExe?.readSL(paramsJson) : window.openExe?.readSLSM(paramsJson) //刷脸
    }

    res = await post('/outp/mzdj/getReadPatientInfo', {
      jsonStr: readCardResult.value,
      mdtrtCertNo: '',
      mdtrtCertType: cardTypeEnum[tabActiveKey.value]?.mdtrtCertType
    })
  }
  if (res.code !== 0) return message.error(res.msg || '读卡失败')
  if (!res.data.ybkResonse?.br_id) return message.error('无病人信息')
  const {
    data = [],
    code,
    msg
  } = await post('/inp/zydj/getInpAppointmentRecordList', {
    brId: res.data.ybkResonse?.br_id
  })
  if (code !== 0) return message.error(msg || '请求失败')
  if (!data || data.length <= 0) return message.error('无病人信息')
  initPatientInfo(data[0])
  isGb.value = res.data.isgb
  accountQueryData.value = res.data || {}
  medFormState.value = { ...data, ...res.data } || {}
  medFormState.value.insureNo = res.data.ybkResonse?.kh
  medFormState.value.ksbm_new = res.data.ybkResonse?.ksbm_new
  medFormState.value.brSfz = res.data.baseinfo?.sfzh
  medFormState.value.insuplc_admdvs = res.data.ybkResonse?.insuplc_admdvs
  if (res.data.yxinsuinfo && res.data.yxinsuinfo.length > 0) {
    // yxinsuinfo 有效险种类别  insuinfo  所有险种类别
    //如果有有效险种类别，默认取第一个
    CHSInfo.value = JSON.parse(JSON.stringify(res.data.yxinsuinfo[0])) //赋值一个险种类别
  } else {
    //没有的话就取所有险种类别第一个
    if (res.data.insuinfo && res.data.insuinfo.length > 0) {
      CHSInfo.value = JSON.parse(JSON.stringify(res.data.insuinfo[0]))
    } else {
      CHSInfo.value = {}
    }
  }
}
const onClickInsureTypeName = (val) => {
  openAccountQueryModal()
  isSixSelect.value = val
}
const openAccountQueryModal = () => {
  if (!medFormState.value.insureNo) {
    if (tabActiveKey.value === '社保卡') return message.warning('请先读取社保卡')
    if (tabActiveKey.value === '身份证') return message.warning('请先读取身份证')
    if (tabActiveKey.value === '电子凭证') return message.warning('请先扫描电子凭证')
    if (tabActiveKey.value === '刷脸授权') return message.warning('请先读取刷脸授权')
    if (tabActiveKey.value === '终端扫码') return message.warning('请先读取终端扫码')
  }
  if (isGb.value) {
    // 国平
    accountQuerySixOpen.value = true
  } else {
    //五期
    accountQueryFiveOpen.value = true
  }
}

const filterType = () => {
  // area为01为上海五期医保单独处理  其余按国家医保处理
  if (inAreaCode.value) {
    const tab = []
    for (const key in cardTypeEnum) {
      if (Object.hasOwnProperty.call(cardTypeEnum, key)) {
        const element = cardTypeEnum[key]
        if (inAreaCode.value === '01') {
          if (element.area === '01' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        } else {
          if (element.area === '00' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        }
      }
    }
    return tab
  } else {
    message.error('请联系管理员设置医保区域代码')
    return []
  }
}

const onSelectCHS = (row) => {
  CHSInfo.value.insutype = row.insutype
  CHSInfo.value.insutypeName = row.insutypeName
  CHSInfo.value.insuplc_admdvs = row.insuplc_admdvs
}
</script>
<style lang="less" scoped>
:deep(.ant-list-items) {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ant-list-item {
    justify-content: center;
    width: 100px;
    height: 60px;
    margin-top: 8px;
    padding: 8px;
    border: 1px solid #eee !important;
    border-radius: 8px;
    cursor: pointer;
    &:hover {
      background-color: #3758f110;
    }
    &.active {
      color: #fff;
      background-color: #3758f1;
      &:hover {
        background-color: #3758f1;
      }
    }
  }
}

:deep(.ant-form) {
  display: flex;
  flex-flow: row wrap;
  min-width: 0;
  .ant-form-item {
    .ant-form-item-label {
      width: 80px;
    }
  }
  .ant-picker {
    width: 100%;
  }
}

.diver {
  width: 1px;
  height: 600px;
  border-style: dashed;
  border-left: 1px;
  border-left-color: #ccc;
}
</style>
